import cv2
import numpy as np

# 读取图片，采用相对路径
img = cv2.imread(r'11.jpg')

enable = False


def call_back_draw(event, x, y, flags, param):
    global enable  # 定义全局变量，修改 enable

    if event == cv2.EVENT_LBUTTONDOWN:  # 鼠标左键按下
        enable = True
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:  # 鼠标移动且左键按下
        if enable:
            drawMask(y, x)
    elif event == cv2.EVENT_LBUTTONUP:  # 鼠标左键抬起
        enable = False


def drawMask(x, y, size=25):  # 图像局部采样函数
    m = np.uint8(x / size) * size
    n = np.uint8(y / size) * size

    for i in range(size):  # size 大小范围内的图像像素值设置为同一个像素值
        for j in range(size):
            img[m + i, n + j] = img[m, n]


# 给窗口命名，这样可以自由调节窗口的大小
cv2.namedWindow('image')
# 鼠标回调函数
cv2.setMouseCallback('image', call_back_draw)

while True:
    # 图像不停地显示
    cv2.imshow('image', img)
    # 按 q 键退出程序
    if cv2.waitKey(1) == ord('q'):
        break

# 退出窗口
cv2.destroyAllWindows()